#include "LinklistwithHead.h"




Head *createlist()
{
    //开辟管理者节点空间，并且初始化
    Head *ph = (Head *)malloc(sizeof(Head));
    ph->first = NULL;
    ph->last = NULL;
    ph->nodenum = 0;
    return ph;
}


void inserTolist(Datatype num,Head *h)
{
    if(h == NULL)
    {
        printf("链表不存在\n");
        return ;
    }
    //为num分配一个节点空间
    PNode pnew = (PNode)malloc(sizeof(Node));
    pnew->data = num;
    pnew->next = NULL;
        if(h->first == NULL)//从无到有
        {
            h->first = pnew;
            h->last = pnew;
        }
        else
        {
            //头插法
            //pnew->next = h->first;
            //h->first = pnew;
            //尾插法
            h->last->next = pnew;
            h->last = pnew;
        }
        h->nodenum++;
}



//查找链表中指定的值x,返回找到的节点的指针,如果没找到则返回NULL
void findValue(Head *h,Datatype x)
{
    //如果链表不存在
    if(h == NULL || h->first == NULL)
    {
        printf("链表不存在");
        //return NULL;
    }
    else//链表存在
    {
        PNode p = h->first;
        
        while(p)//p存在
        {
            if(p->data != x)//p->data不等于x
            {
                if(p->next == NULL)
                {
                    printf("NULL");
                }
                p = p->next;
            }
            else//找到
            {
                printf("%d\n",p->data);
                break;
            }
        }
    }
}



bool haIsSonOfnb(Head *ha,Head *hb)
{
    if(ha == NULL || ha->first == NULL)
    {
        return true;
    }
    PNode pa = ha->first;
    PNode pb = hb->first;
    PNode pf = NULL;
    while(pa && pb)//两个链表都没走到头
    {
        if(pa->data == pb->data)
        {
            pa = pa->next;
            pb = pb->next;
        }
        else//不对的话，A返回，first，B返回下一个节点
        {
            pa = ha->first;
            if(pa->data != pb->data)
            {
                pb = pb->next;
            }
        }
    }
    if(pa == NULL)
    {
        return true;
    }
    else
    {
        return ;
    }
}




//返回一个链表中，倒数第k的节点的指针




//判断单链表是否存在环





/*--------------------------------------------------------------------*/
void printflist(Head *h)
{
    PNode p = h->first;
    while(p)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
}

void clearlist(Head *head)
{
   if(head == NULL || head->first == NULL)
   {
        return ;
   }
   //一个一个的释放节点
   while(head->first)
   {
    Node *p = head->first;
    head->first = p->next;
    p->next = NULL;
    free(p);
    head->nodenum--;
   }
   head->last = NULL;
}

void deletelist(Head *h)
{
    //清空整个链表
    clearlist(h);
    //释放头结点
    free(h);
}


